package cn.javadog.cloud.starter.jsonfilter.converter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import cn.javadog.cloud.starter.jsonfilter.domain.JsonFilterObject;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageNotWritableException;

import java.io.IOException;
import java.io.OutputStream;
import java.util.Arrays;

import static com.alibaba.fastjson.util.IOUtils.UTF8;

/**
 * @author yuy
 * @date 2020-11-09 15:01
 **/
public class JsonFilterHttpMessageConverter extends FastJsonHttpMessageConverter {

    private static final SerializerFeature[] FEATURES = new SerializerFeature[]{SerializerFeature.PrettyFormat,
            SerializerFeature.WriteMapNullValue,
            SerializerFeature.WriteNullStringAsEmpty,
            SerializerFeature.DisableCircularReferenceDetect,
            SerializerFeature.WriteNullListAsEmpty};

    public JsonFilterHttpMessageConverter() {
        super();
        setSupportedMediaTypes(Arrays.asList(
                new MediaType("application", "json", UTF8),
                new MediaType("application", "*+json", UTF8),
                new MediaType("application", "jsonp", UTF8),
                new MediaType("application", "*+jsonp", UTF8)));
        FastJsonConfig fastJsonConfig = new FastJsonConfig();
        fastJsonConfig.setSerializerFeatures(FEATURES);
        setFastJsonConfig(fastJsonConfig);
    }

    @Override
    public boolean supports(Class<?> clazz) {
        // void 是基础类型
        return String.class != clazz && !clazz.isPrimitive();
    }

    /**
     *
     * @param obj- the object to write to the output message
     * @param outputMessage- the HTTP output message to write to
     * @throws IOException- in case of I/O errors
     * @throws HttpMessageNotWritableException- in case of conversion errors
     * 官方地址：https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/http/converter/AbstractGenericHttpMessageConverter.html#writeInternal-T-org.springframework.http.HttpOutputMessage-
     */
    @Override
    protected void writeInternal(Object obj, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {
        if (obj instanceof JsonFilterObject) {
            JsonFilterObject jsonFilterObject = (JsonFilterObject) obj;
            SimpleSerializerFilter simpleSerializerFilter = new SimpleSerializerFilter(jsonFilterObject);
            String text = JSON.toJSONString(jsonFilterObject.getData(), simpleSerializerFilter, FEATURES);
            OutputStream out = outputMessage.getBody();
            byte[] bytes = text.getBytes();
            out.write(bytes);
        }else {
            super.writeInternal(obj, outputMessage);
        }
    }
}
